package ru.ipo.dces.server;

import ru.ipo.dces.clientservercommunication.*;
import ru.ipo.dces.exceptions.GeneralRequestFailureException;
import ru.ipo.dces.exceptions.ServerReturnedError;
import ru.ipo.dces.utils.ResponseHandler;

import javax.swing.*;

public class ServerFacadeAsynchronous {

    private ServerFacade server;

    public ServerFacadeAsynchronous(ServerFacade server) {
        this.server = server;
    }

    public <Resp extends Response> void doRequest(final Request request, final ResponseHandler<Resp> handler) {
        Thread requestThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final Resp response = (Resp) server.doRequest(request);
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            handler.success(response);
                        }
                    });

                } catch (final ServerReturnedError e) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            handler.fail(new ServerFailReason(e, ServerFailReason.ServerExceptionType.ServerReturnedError));
                        }
                    });
                } catch (final GeneralRequestFailureException e) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            handler.fail(new ServerFailReason(e, ServerFailReason.ServerExceptionType.GeneralRequestFailureException));
                        }
                    });
                }
            }
        });
        requestThread.start();
    }
}